package org.keyyond.ms.core.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

@Component
public class ApplicationContextProvider implements ApplicationContextAware {

    @Autowired
    private static ApplicationContext applicationContext;

    // 设置上下文
    public void setApplicationContext(ApplicationContext applicationContext) {
	ApplicationContextProvider.applicationContext = applicationContext;
    }

    // 获取applicationContext
    public static ApplicationContext getApplicationContext() {
	return applicationContext;
    }

    // 通过name获取 Bean.
    public static Object getBean(String name) {
	return getApplicationContext().getBean(name);
    }

    // 通过class获取Bean.
    public static <T> T getBean(Class<T> clazz) {
	return getApplicationContext().getBean(clazz);
    }

    // 通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name, Class<T> clazz) {
	return getApplicationContext().getBean(name, clazz);
    }
    
//       /**
//	 * 根据类对象获得spring容器中的bean对象
//	 * @param clazz 类对象
//	 * @return bean对象
//	 */
//	public static Object getBean(Class clazz) {
//		WebApplicationContext wac = ContextLoader
//				.getCurrentWebApplicationContext();
//		Object bean = wac.getBean(clazz);
//		return bean;
//	}

}
